<!-- components/Account.vue -->
<template>
	<view class="container">
		<!-- 标题 -->
		<!-- <CustomNavbar title="支付订单" /> -->
		<view class="content">
			<view class="top">
				<text class="time">
					支付剩余时间{{time}}
				</text>
				<text class="pay_tip">
					支付金额
				</text>
				<view class="price">
					￥<text>{{payInfo?.order_amount}}</text>
				</view>

			</view>
			<view class="main">
				<h4>选择支付方式</h4>
				<view class="pay_type flex-between" v-for="(item,index) in payList" :key="index"
					@click="selectPayType(item,index)">
					<view class="left">
						<image :src="item.icon" mode=""></image>
						<text>{{item.type}}</text>
						<!-- <text class="price" v-if="item.price!=0">(￥{{item.price}})</text> -->
					</view>
					<view class="right">
						<image :src="index===payIndex?item.checkedIcon:item.checkIcon" mode=""></image>
					</view>
				</view>
			</view>
		</view>
		<button @click="query">确认付款</button>
		<pay-password v-model:visible="showPayPassword" :amount="payInfo?.order_amount" @complete="handlePayComplete"
			@forget="handleForgetPassword" />
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted,
		onUnmounted
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import CustomNavbar from '@/components/CustomNavbar.vue';
	import PayPassword from '@/components/PayPassword.vue';
import { isNumber } from 'lodash';
	const id = ref(null);
	const goods_id = ref(null);
	const showPayPassword = ref(false)
	const payInfo = ref()
	onLoad((options) => {
		id.value = options.order_id
		goods_id.value = options.goods_id
		getPayType()
		// getDetail()
	})
	const formData = ref(null)
	// 倒计时
	// 总时间（30分钟 = 1800秒）
	const totalSeconds = ref(1800);
	let timer = null;
	const time = ref(0)
	const newDate = ref(0)

	// 启动计时器
	const startTimer = () => {
		const orderTimestamp = payInfo.value.createtime
		timer = setInterval(() => {
			const nowDate = new Date().getTime();
			newDate.value = Math.floor(nowDate / 1000);
			const remainingTime = orderTimestamp + 1800 - newDate.value;
			// 如果时间到，清除定时器
			if (remainingTime <= 0) {
				clearInterval(timer);
				return;
			}

			// 将毫秒转换为小时、分钟、秒
			const hours = Math.floor(remainingTime / 3600);
			const minutes = Math.floor((remainingTime % 3600) / 60);
			const seconds = remainingTime % 60;
			// 格式化显示
			time.value =
				`${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
		}, 1000);
	};
	// 组件挂载时启动
	// onMounted(startTimer);

	// 组件卸载时清除定时器
	onUnmounted(() => {
		clearInterval(timer);
	});

	// 支付方式
	const payIndex = ref(0)
	const payType = reactive([{
			type: '微信',
			icon: '/orderPages/static/wechat.png',
			checkIcon: '/orderPages/static/check.png',
			checkedIcon: '/orderPages/static/checked.png'
		},
		{
			type: '支付宝',
			icon: '/orderPages/static/alipay.png',
			checkIcon: '/orderPages/static/check.png',
			checkedIcon: '/orderPages/static/checked.png'
		},
		{
			type: '现金账户',
			icon: '/orderPages/static/cash.png',
			checkIcon: '/orderPages/static/check.png',
			checkedIcon: '/orderPages/static/checked.png'
		},
		{
			type: '复消账户',
			icon: '/orderPages/static/balance.png',
			checkIcon: '/orderPages/static/check.png',
			checkedIcon: '/orderPages/static/checked.png'
		},
		{
			type: '积分账户',
			icon: '/orderPages/static/balance.png',
			checkIcon: '/orderPages/static/check.png',
			checkedIcon: '/orderPages/static/checked.png'
		},
	])
	const payList = ref([])
	const selectPayType = (item, index) => {
		payIndex.value = index
	}
	const objValue = (obj) => {
		const valuesArray = Object.values(obj);
		const keysArray = Object.keys(obj);
		const objArr = valuesArray.map((item, i) => {
			return {
				id: keysArray[i],
				type: item
			}

		})

		return objArr;
	}
	const getPayType = () => {
		uni.$api.order.payType({
			id: id.value
		}).then(res => {
			if (res.code == 200) {
				payList.value = objValue(res.data.pay_type).map(item => {
					const matchedItem = payType.find(it => it.type == item.type);
					if (matchedItem) {
						return {
							...item,
							...matchedItem
						};
					}
				})
				payInfo.value = res.data.order
				startTimer()
			}
		})
	}
	// 支付完成回调
	const handlePayComplete = (password) => {
		uni.showLoading({
			title: '支付处理中...'
		})

		uni.hideLoading()
		uni.$api.order.payPwd({
			pay_password: password
		}).then(res => {
			if (res.code == 200) {
				console.log(0)
				onPay()
			}
			setTimeout(function() {
				showPayPassword.value = false
				
			}, 1000)
		}).catch(err => {
			setTimeout(function() {
				showPayPassword.value = false
			}, 1000)
		})
	}

	// 忘记密码
	const handleForgetPassword = () => {
		uni.showModal({
			title: '提示',
			content: '请通过安全中心重置支付密码',
			showCancel: false
		})
	}
	const buildQueryString = function(params) {
		// 步骤2：构建完整URL
		return `https://openapi.alipay.com/gateway.do?${
    Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')
  }`;;
	}

	// 支付
	const h5Pay = function(res) {
		// 微信H5支付
		if (payIndex.value) {
			window.location.href = `https://pay.weixin.qq.com?orderId=${payIndex.value.orderId}`;
			return;
		}

		// 支付宝H5支付
		if (!payIndex.value) {
			const divForm = document.getElementsByTagName('divform');
			if (divForm.length) {
				document.body.removeChild(divForm[0])
			}
			const div = document.createElement('divform');
			div.innerHTML = res; // data就是接口返回的form 表单字符串
			document.body.appendChild(div);
			let len = document.forms.length - 1;
			document.forms[len].setAttribute('target', '_blank'); // 新开窗口跳转
			document.forms[len].submit();
			return;
		}
	}

	const appPay = function(res) {
		const data = parseQueryString(res)
		uni.requestPayment({
			provider: payIndex.value ? 'alipay' : 'wxpay',
			orderInfo: JSON.stringify(data.biz_content),
			success: (res) => {
				console.log('支付成功', res);
				uni.showToast({
					title: '支付成功'
				});
			},
			fail: (err) => {
				console.log('支付失败', err);
				uni.showToast({
					title: '支付失败',
					icon: 'none'
				});
			}
		});
	}

	function parseQueryString(queryString) {
		return queryString.split('&').reduce((params, pair) => {
			const [key, value] = pair.split('=')
			params[key] = decodeURIComponent(value || '')
			return params
		}, {})
	}
	// 确认
	const query = () => {
		if (payList.value[payIndex.value].id > 2) {
			return showPayPassword.value = true;
		}
		onPay()
		
	}
	const onPay = ()=> {
		// #ifdef H5
		const method = 'wap';
		// #endif

		// #ifdef APP-PLUS
		const method = 'app'
		// #endif
		uni.$api.order.goPay({
			id: id.value,
			pay_type: payList.value[payIndex.value].id,
			method: method
		}).then(res => {
			if (res.code == 200) {
				if (payList.value[payIndex.value].id > 2) {
					uni.showToast({
						title: res.msg
					})
					setTimeout(function() {
						uni.navigateTo({
							url: '/orderPages/pages/order/pay-success'
						})
					}, 1000)
				} else {
					// #ifdef H5
					h5Pay(res.data);
					// #endif
		
					// #ifdef APP-PLUS
					appPay(res.data);
					// #endif
				}
		
			}
		})
		
	}
</script>

<style lang="scss" scoped>
	page{
		background-color: #EFF2F6;
	}
	.container {

		background: url('/static/index_slices/index_bg.png') no-repeat;
		background-size: 100% auto;
		padding-top: 8rpx;
		padding-bottom: 80rpx;

		/* 导航栏高度 */
		.content {
			// 支付信息
			margin: 20rpx;
			border-radius: 26rpx;
			background-color: #fff;
			padding-top: 81rpx;
			padding-bottom: 104rpx;

			.top {
				color: #2D2E37;
				font-size: 32rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				margin-bottom: 170rpx;

				.time {
					color: #999999;
					font-size: 28rpx;
				}

				.pay_tip {
					margin: 30rpx 0 39rpx;
				}

				.price {
					color: #121922;

					font-size: 40rpx text {
						font-size: 50rpx
					}
				}
			}

			// 选择支付类型
			.main {

				h4 {
					margin: 0 23rpx;
					padding: 31rpx 52rpx;
					position: relative;
					color: #202224;
					font-size: 32rpx;
					border-bottom: 1px dashed #EEE7E7;

					&::after {
						content: '';
						display: block;
						width: 12rpx;
						height: 40rpx;
						border-radius: 6rpx;
						background-color: #FD3832;
						position: absolute;
						left: 21rpx;
						top: 36rpx;
					}
				}

				.pay_type {
					padding: 48rpx 30rpx 25rpx 44rpx;
					color: #101624;
					font-size: 28rpx;

					.left {
						display: flex;
						align-items: center;

						image {
							width: 48rpx;
							height: 48rpx;
							margin-right: 13rpx;
						}

						.price {
							font-size: 26rpx;
							color: #999;
							padding-left: 10rpx;
						}
					}

					.right {
						image {
							width: 35rpx;
							height: 35rpx;
						}
					}
				}
			}
		}


		// 确认
		button {
			position: fixed;
			left: 30rpx;
			bottom: 47rpx;
			width: 690rpx;
			height: 88rpx;
			line-height: 88rpx;
			border-radius: 44rpx;
			font-size: 32rpx;
			background: linear-gradient(to right, #FF5A55, #FD3832);
			color: #fff;

		}
	}
</style>